package com.hsb.seckill.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsb.seckill.entity.User;
import com.hsb.seckill.result.ResBean;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;

/**
 * 生成用户工具类
 */
public class UserUtil {
    private static void createUser(int count) throws IOException, SQLException, ClassNotFoundException {
        ArrayList<User> users = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            User user = new User();
            long num = 13000000000L+i;
            user.setMobile(String.valueOf(num));
            user.setNickname("user"+i);
            user.setSlat("1a2b3c4d");
            user.setPassword(MD5Util.inputPassToDBPass("123456",user.getSlat()));
            user.setLoginCount(1);
            user.setRegisterDate(new Date());
            users.add(user);
        }
        System.out.println("create User");
        //插入数据库
        Connection conn = getConn();
		String sql = "insert into t_user(login_count, nickname, register_date, slat, password, mobile)values(?,?,?,?,?,?)";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		for(int i=0;i<users.size();i++) {
			User user = users.get(i);
			pstmt.setInt(1, user.getLoginCount());
			pstmt.setString(2, user.getNickname());
			pstmt.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
			pstmt.setString(4, user.getSlat());
			pstmt.setString(5, user.getPassword());
			pstmt.setString(6, user.getMobile());
			pstmt.addBatch();
		}
		pstmt.executeBatch();
		pstmt.close();
		conn.close();
		System.out.println("insert to db");

        //登录，生成token
        String urlString = "http://localhost:8080/login/doLogin";
        File file = new File("C:/Users/H/Desktop/config.txt");
        if(file.exists()) {
            file.delete();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        file.createNewFile();
        raf.seek(0);
        for(int i=0;i<users.size();i++) {
            User user = users.get(i);
            URL url = new URL(urlString);
            HttpURLConnection co = (HttpURLConnection)url.openConnection();
            co.setRequestMethod("POST");
            co.setDoOutput(true);
            OutputStream out = co.getOutputStream();
            String params = "mobile="+user.getMobile()+"&password="+MD5Util.inputPassToFromPass("123456");
            out.write(params.getBytes());
            out.flush();
            InputStream inputStream = co.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buff)) >= 0) {
                bout.write(buff, 0 ,len);
            }
            inputStream.close();
            bout.close();
            String response = new String(bout.toByteArray());
            System.out.println(response);
            ObjectMapper mapper = new ObjectMapper();
            ResBean resBean = mapper.readValue(response, ResBean.class);
            String userTicket = (String) resBean.getObj();
            System.out.println("create token : " + user.getMobile());

            String row = user.getMobile()+","+userTicket;
            raf.seek(raf.length());
            raf.write(row.getBytes());
            raf.write("\r\n".getBytes());
            System.out.println("write to file : " + user.getMobile());
        }
        raf.close();
        System.out.println("over");

    }

    private static Connection getConn() throws ClassNotFoundException, SQLException {
        String driver= "com.mysql.cj.jdbc.Driver";
        String url ="jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String username= "root";
        String password = "H8888";
        Class.forName(driver);
        return DriverManager.getConnection(url,username,password);
    }

    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        createUser(5000);
    }
}
